<?php
/**
 * User: @lose
 * Date: 2022/7/7
 * Time: 14:14
 */

namespace Frieza\Modules\Photo\Controllers;

use App\Pockets\GridDataModel as pGridDataModel;
use Doraemon\cache\Queue;
use Doraemon\model\AdmNoteOutlineLog;
use Doraemon\model\AdmNoteRemark;
use Doraemon\model\Photos as mPhotos;
use Doraemon\model\TopicActivity;
use Doraemon\service\AdmNote;
use Doraemon\service\Circle\PhotosCircle;
use Doraemon\service\DecorationTask\Read;
use Doraemon\service\Note\NoteHandle;
use Doraemon\service\Photos;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Grid\Displayers\DropdownActions;
use Encore\Admin\Layout\Content;
use Doraemon\model\AdmPhotoViolation;
use Encore\Admin\Layout\Row;
use Encore\Admin\Widgets\Box;
use Frieza\Modules\Photo\Actions\Normal;
use Frieza\Modules\Photo\Actions\BanUser;
use Frieza\Modules\Photo\Actions\FansView;
use Illuminate\Http\Request;
use Doraemon\model\AdmRecommendUser;
use Doraemon\model\BestUser;
use Doraemon\model\Member;
use Doraemon\model\AdmOperateLog;
use Doraemon\cache\Photos as cPhotos;
use Frieza\Modules\Photo\Extensions\BatchNormal;

class ViolationController
{
    public function index(Content $content, Request $request)
    {
        $time = $request->input('time', date('Y-m-d', strtotime('-7 day')));
        $page = $request->input('page', 1);
        $pageSize = $request->input('per_page', 15);
        $limit = [($page - 1) * $pageSize, $pageSize];

        $violationList = AdmPhotoViolation::getList($time, $limit);
        $violationList = $violationList?:[];
        $total = AdmPhotoViolation::getTotal($time);
        $ids = array_column($violationList, 'photo_id');
        $kids = array_column($violationList, 'id');
        $photos = Photos::getPhotos($ids); // 通过id获取图片信息

        //话题信息
        $topicIds = empty($photos) ? [] : array_column($photos, 'topic_activity_id');
        $topicInfos = TopicActivity::getByIds($topicIds);
        $topicInfosRegular = $topicInfos ? array_column($topicInfos, null, 'id') : [];

        $diaryList = $diaryIds = $circleList = $circleIds = [];
        // 获取关联信息
        foreach ($photos as $photo) {
            if ($photo['type'] == mPhotos::TYPE_DIARY) {
                $diaryIds[] = $photo['id'];
            }
            if ($photo['type'] == mPhotos::TYPE_CIRCLE) {
                $circleIds[] = $photo['id'];
            }
        }

        if ($diaryIds) {
            $diaryList = Read::getDiaryByDiaryIds($diaryIds);
        }

        if ($circleIds) {
            $circleList = PhotosCircle::selectPhotoCircle($circleIds);
        }

        foreach ($violationList as &$info) {
            $photo = $photos[$info['photo_id']];
            $info['title'] = $photo['title'];
            $info['remark'] = $photo['remark'];
            $info['type'] = $photo['type'];
            $info['addtime'] = $photo['addtime'];
            $info['topic_activity_id'] = $photo['topic_activity_id'];
            $info['topic_info'] = $topicInfosRegular[$photo['topic_activity_id']];
            $info['article_id'] = $photo['article_id'];

            if ($photo['type'] == mPhotos::TYPE_DIARY) {
                $info['title'] = $diaryList[$info['photo_id']]['title'];
                $info['task_id'] = $diaryList[$info['photo_id']]['task_id'];
            }
            if ($photo['type'] == mPhotos::TYPE_CIRCLE) {
                $info['name'] = $circleList[$photo['id']]['circle_name'];
                $info['circle_id'] = $circleList[$photo['id']]['circle_id'];
            }

            $info['expand'] = $this->_getPicExpand($info);
        }
        $gridModel = new pGridDataModel($violationList, $total, [
            'keyName' => 'id'
        ]);

        $listGrid = Admin::grid($gridModel, function (Grid $grid) {

            $grid->tools(function ($tools) {
                $tools->batch(function ($batch) {
                    $batch->disableDelete();
                    $batch->add('批量正常', new BatchNormal());
                });
            });

            $grid->disableExport();
            $grid->disableCreateButton();
            $grid->setActionClass(DropdownActions::class);
            $grid->expandFilter();
            $grid->filter(function (Grid\Filter $filter){
                $filter->disableIdFilter();
                $filter->column(1 / 2, function (Grid\Filter $filter) {
                    $filter->date('time', '起始时间')->default(date('Y-m-d H:i:s', strtotime('-7 day')));
                });
            });

            $grid->hideColumns('id');
            $grid->column('photo_id', '内容id')->expand(function () {
                return $this->expand;
            }, true)->width(90);
            $grid->column('uid', '用户信息')->userBasicInfo()->width(150);
            $grid->column('remark', '图说')->display(function () {
                $s2 = preg_replace("/#.*?\s/", '', $this->remark . $this->title);
                $s3 = preg_replace("/\\[.*?]/", '', $s2);
                $s4 = preg_replace("/(\s|\&nbsp\;|　|\xc2\xa0)/", "", strip_tags($s3));
                return "<strong>[字数]: </strong>" .
                    mb_strlen($s4) . "<br><strong>[标题]:</strong>{$this->title}<br><strong>[正文]:</strong><br>" . str_replace(' ', '&nbsp;', nl2br($this->remark));
            })->width(350);
            $grid->column('relation', '关联操作')->display(function () {
                $addtime = date('Y-m-d H:i:s', $this->addtime);
                $content = "<a href='/admin/photo/photocheck/index?photo_id=$this->photo_id' target='_blank'>审核note</a><br/>";

                if ($this->article_id) {
                    $content .= "<br/><a href='/admin/article/select/audit/$this->article_id' target='_blank'>审核整屋</a><br/>";
                }

                if ($this->topic_activity_id) {
                    $content .= "<br/>话题id:<a href='/admin/photo/answer/list?photo_id=$this->photo_id' target='_blank'>$this->topic_activity_id</a><br>话题标题：" . $this->topic_info['title'] . "<br/>";
                }

                if ($this->circle_id) {
                    $content .=  "<br/> 圈子id: <a href='/admin/circle/photos/list?photos_id=$this->photo_id' target='_blank'>$this->circle_id</a> <br> 圈子名称：{$this->name}<br/>";
                }
                return $content . "<br/>发布时间: $addtime";
            })->width(220);
            $grid->column('violation_info', '违规信息')->display(function () {
                $violationInfo = json_decode($this->violation_info,true);
                $string = "";
                if (isset($violationInfo['data'])) {
                    foreach ($violationInfo['data'] as $info) {
                        $string .= $info['msg'];
                    }
                } else if (isset($violationInfo['ads'])) {
                    $string .= "<span style='color: red'>含有广告    </span>" . implode(',', $violationInfo['ads']['texts']);
                } else {
                    $reason = [];
                    if (is_array($violationInfo)) {
                        foreach ($violationInfo as $info) {
                            $reason[] = $info['data'][0]['msg'];
                        }
                        $string .= implode('、', array_unique($reason));
                    }
                }

                $violationType = AdmPhotoViolation::VIOLATION_TYPE_DESC[$this->violation_type];
                return AdmPhotoViolation::API_DESC[$this->api_type] . "识别: <span style='color: red'>{$violationType}</span><br>违规原因: $string";
            });

            $grid->actions(function (Grid\Displayers\Actions $actions) {
                $actions->disableDelete();
                $actions->disableEdit();
                $actions->disableView();
                $actions->add(new Normal);
                $actions->add(new BanUser);
                $actions->add(new FansView);
            });
            $grid->footer(function () {
                $html = '<input class="btn btn-sm btn-success fa-trash" type="submit" id="tj_sub" value="本页一键置为正常" style="margin-right: 100px;width: 130px;height: 35px">';
                return $html;
            });
        });

        Admin::script($this->imgScript());
        Admin::script($this->pageScript($kids));

        return $content
            ->header('自动识图审核')
            ->row("<div style='position:fixed;z-index:10000;top:50px;left:35%;width:600px;height:600px;' class='imgMoveDiv'><img src='' alt='' class='imgMove' style='width:auto;height:auto;max-width:100%;max-height:100%;'></div>")
            ->body($listGrid);
    }

    private function _getPicExpand($info)
    {
        $url = $info['photo_url'];
        $urlList = explode(',', $url);
        $row = new Row();
        $row->column(12, implode("", array_map(function ($url) {
            return "<img class='img-responsive float-left center-block col-md-2 img' src='{$url}' />";
        }, $urlList)));
        $box = new Box('图片信息' . '  (数量:' . count($urlList) . ')');
        $box->solid()->content($row->render());
        return $box->render();
    }

    // 将note置为正常状态
    public function setNormal(Request $request)
    {
        $id = $request->input('_key');
        $this->updateCheckStatus($id);
        AdmPhotoViolation::update(['status' => AdmPhotoViolation::STATUS_YES], ['id' => $id]);

        return response()->json($this->getResponse('成功设为正常图片'));
    }

    // 批量置为正常
    public function batchNormal(Request $request)
    {
       $ids = $request->input('ids');
        $data = [
            'admin_id' => Admin::user()->id,
            'status' => AdmPhotoViolation::STATUS_YES,
            'check_status' => AdmPhotoViolation::CHECK_STATUS_YES,
            'check_time' => time()
        ];
        AdmPhotoViolation::update($data, ['id' => $ids]);
    }

    // 本页置为正常
    public function pageNormal(Request $request)
    {
        $ids = $request->input('ids');
        $ids = json_decode($ids,1);
        $data = [
            'admin_id' => Admin::user()->id,
            'status' => AdmPhotoViolation::STATUS_YES,
            'check_status' => AdmPhotoViolation::CHECK_STATUS_YES,
            'check_time' => time()
        ];
        AdmPhotoViolation::update($data, ['id' => $ids]);
        $status = true;
        $message = "操作成功";
        return response()->json(compact('status', 'message'));
    }

    // B1并冻结用户
    public function banUser(Request $request)
    {
        $id  = $request->input('_key');
        $this->updateCheckStatus($id);
        $uid = AdmPhotoViolation::get('uid', ['id' => $id]);
        AdmRecommendUser::delete(['uid' => $uid]); // 从推荐用户中删除
        BestUser::delete(['uid' => $uid]); // 从运营标记优质用户中删除
        $res = Member::update(['status' => Member::STATUS_FROZEN], ['uid' => $uid])->rowCount(); // 将用户状态改为已封禁
        if ($res) {
            Queue::insertQueue('User/frozen_user', ['uid' => $uid]);
            Queue::insertQueue('User/delTokenCache', ['uid' => $uid]);
            AdmOperateLog::addLog($uid, AdmOperateLog::$operate_type['frozen_user'], Admin::user()->id, Admin::user()->find(Admin::user()->id)->name);
            $response = $this->getResponse('成功B1并冻结此账号');
        } else {
            $response = $this->getResponse('请求失败，请重试', 'error');
        }
        return response()->json($response);
    }

    // 仅粉丝可见
    public function fansView(Request $request)
    {
        $id = $request->input('_key');
        $msg = $request->input('text');

        $violationInfo = AdmPhotoViolation::get(['uid', 'photo_id']);
        $noteId = $violationInfo['photo_id'];
        $uid = $violationInfo['uid'];
        if ($noteId && $uid) {
            NoteHandle::remarkNote($noteId, AdmNoteRemark::REMARK_FANS);
            $res = mPhotos::updatePhotoById($noteId, [
                'status' => mPhotos::STATUS_SUCCESS,
                'admin_score' => 5,
                'quality' => mPhotos::QUALITY_LOW,
                'show_status' => mPhotos::SHOW_STATUS_PRIVATE_FLOW
            ]);

            if ($res) {
                AdmNote::auditLog($noteId, mPhotos::QUALITY_LOW, Admin::user()->name, AdmNoteOutlineLog::AUDIT_CHANNEL_VIOLATION_NOTE); // 记录note操作日志
                $this->updateCheckStatus($id); // 更新自动识图表的状态
                cPhotos::delete($noteId); // 删除缓存
                queue::insertQueue('Photo/afterAudit', array(
                    'photo_id' => $noteId
                ));
                if ($msg) {
                    queue::insertQueue('queue/Sysmsg/Send' ,
                        [
                            'msgCode' => 0,
                            'to_uid' => $violationInfo['uid'],
                            'msgParams' => [
                                'from_uid' => 11941,
                                'title' => '违规处理',
                                'detail' => $msg
                            ]
                        ], Queue::QUEUE_DORAEMON
                    );
                }
            }
            return response()->json($this->getResponse());
        }
        return response()->json('操作失败', 'error');
    }

    private function updateCheckStatus($id)
    {
        $data = [
            'admin_id' => Admin::user()->id,
            'check_status' => AdmPhotoViolation::CHECK_STATUS_YES,
            'check_time' => time()
        ];
        AdmPhotoViolation::update($data, ['id' => $id]);
    }

    private function getResponse($content = '操作成功', $type = 'success')
    {
        return [
            'status' => true,
            'then' => [
                'action' => 'refresh',
                'value'  => true,
            ],
            'toastr' => [
                'type' => $type,
                'content' => $content,
                'options' => [
                    'positionClass' => 'toast-top-center'
                ]
            ]
        ];
    }

    private function imgScript()
    {
        return <<<SCRIPT
            $('.imgMoveDiv').hide();
            $('.img').click(function() {
                $('.imgMove').attr('src', $(this).attr('src'));
                $('.imgMoveDiv').show();      
            });
            $('.imgMoveDiv').click(function() {
                $('.imgMoveDiv').hide();      
            });

SCRIPT;
    }

    private function pageScript($ids)
    {

        $js = "var ids = '" . json_encode($ids) . "'";

        $js .=  <<<SCRIPT

        $('#tj_sub').unbind('click').click(function() {
            layer.confirm('确定提交么？', {
                btn: ['确定', '取消']
                
            }, function (index) {
                var url = '/admin/photo/violation/pageNormal'
                var params = {
                    ids:ids
                };
                $.post(url,params,function (result){
                    if (result.status == 1){
                        layer.msg(result.message);
                        setTimeout(function () {
                            parent.window.location.reload();
                        }, 1000);
                    }else{
                        layer.msg(result.message);
                    }
                });
                layer.msg(result.message);
            });
    
		});
SCRIPT;
        return $js;
    }
}